<?php

namespace wechatpay\includes;

use PDO;

class Query
{

    public $link;
    function __construct()
    {
        $this->link = new PDO("mysql:host=127.0.0.1;port=3306;dbname=wxpay", 'root', 'root');
        $this->link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $this->link->query("set names utf8");
        date_default_timezone_set('PRC');
        return $this->link;
    }

//读取缓存
    function GetCache($name)
    {
        $data = null;
        $name = "cache/" . md5($name);
        //判断是否有缓存文件
        if (file_exists($name)) {
            $data = file_get_contents($name);
            $data = unserialize($data);
        }
        return $data;

    }

//读取数据库字段
    function GetFiled($tablename)
    {
        $data = $this->GetCache($tablename);
        //如果有缓存文件直接返回缓存
        if ($data)
            return (object)$data;
        //获取数据库字段
//        $link = DbLink();
        $sql = "SELECT * FROM $tablename";
        $ret = $this->link->query($sql);
        $row = $ret->columnCount();
        $filed_array = array();
        for ($i = 0; $i <= $row; $i++) {

            $filed_array[$ret->getColumnMeta($i)['name']] = null;

        }
        //将数据库字段保存缓存文件
        $this->cache($tablename, (object)$filed_array);
        return (object)$filed_array;
    }

//创建缓存
    function cache($name, $data)
    {
        //序列化缓存
        $msg = serialize($data);
        $name = md5($name);
        //生成缓存文件
        file_put_contents("cache/$name", $msg);
    }

//预处理添加
    function ObjectSqlInsert($obj, $tablename = "")
    {

        if ($tablename == "")
            $tablename = strtolower(get_class($obj));
        $fields = array();
        $values = array();
        foreach ($obj as $key => $value) {
            if ($key == "id" && $value == 0)
                continue;
            $fields [] = $key;
            $values[] = "?";
            $val [] = $value;
        }
        $sql = "INSERT INTO " . $tablename . " (" . implode(",", $fields) . ") VALUES (" . implode(",", $values) . ")";
        $ret = $this->link->prepare($sql);
        for ($i = 0; $i < count($val); $i++) {
            $j = $i + 1;
            $ret->bindValue($j, $val[$i]);
        }
        $bools = $ret->execute();
        if ($bools)
            $obj->id = $this->link->lastInsertId($sql);
        return $ret;
    }

//数据合并
    function ObjectFromArray($obj, $row)
    {
        $ret = array();
        foreach ($obj as $key => $value) {
            if (array_key_exists($key, $row)) {
                if (is_bool($obj->$key))
                    $ret[$key] = $row[$key] == "1";
                else
                    if (is_array($obj->$key) && is_string($row[$key]))
                        $ret[$key] = explode(",", $row[$key]);
                    else
                        if (is_string($obj->$key) && is_array($row[$key]))
                            $ret[$key] = implode(",", $row[$key]);
                        else
                            if (is_string($obj->$key) && is_string($row[$key]))
                                $ret[$key] = stripslashes($row[$key]);
                            else
                                $ret[$key] = $row[$key];
            }
        }
        return (object)$ret;
    }

//多数据查询
    function ObjectSqlsLoad($sql, $classname)
    {

        $res = $this->link->query($sql);
        if ($res != FALSE && $res->rowCount() > 0) {
            $ret = array();
            $res->setFetchMode(PDO::FETCH_ASSOC);
            //$obj = new $classname();
            while ($row = $res->fetch()) {
                $ret[] = $this->ObjectFromArray($classname, $row);
                //$ret[] = $classname;
            }
            return $ret;
        } else
            return FALSE;
    }

//查询一条数据
    function ObjectSqlLoad($obj, $tablename = "")
    {


        if ($tablename == "")
            $tablename = strtolower(get_class($obj));
        if ($obj->id == 0)
            return;

        $sql = "SELECT * FROM " . $tablename . " WHERE id = ?";
        $res = $this->link->prepare($sql);
        $res->bindValue(1, $obj->id);
        $bools = $res->execute();
        if ($bools != FALSE && $res->rowCount() == 1) {
            $res->setFetchMode(PDO::FETCH_ASSOC);
            $row = $res->fetch();
            $ret = $this->ObjectFromArray($obj, $row);
            return $ret;
        } else {
            return false;
        }
    }

    function ObjectSqlUpdate($obj, $tablename = "")
    {

        if ($tablename == "")
            $tablename = strtolower(get_class($obj));
        $fields = array();
        foreach ($obj as $key => $value) {
            //这里把id过滤了，因为不更新id
            if ($key == "id")
                continue;
            $fields [] = $key . "=" . "'" . $value . "'";
        }
        $sql = "UPDATE " . $tablename . " SET " . implode(",", $fields) . " WHERE id = ?";
//    echo $sql;
        $res = $this->link->prepare($sql);
        $res->bindValue(1, $obj->id);
        $bools = $res->execute();

        return $bools;
    }

    function GetCount($sql)
    {

        $rs = $this->link->query($sql);
        $count = $rs->rowCount();
        return $count;
    }

    function GetObjectBySql($sql, $classname, $where_array = array())
    {

        $res = $this->link->prepare($sql);
        $bools = $res->execute($where_array);
        if ($bools !== FALSE && $res->rowCount() > 0) {
            $res->setFetchMode(PDO::FETCH_ASSOC);
            $row = $res->fetch();
            $obj = new $classname;
            $ret = $this->ObjectFromArray($obj->filed, $row);
            return $ret;
        } else
            return FALSE;
    }

    function ObjectSqlSave($obj, $tablename = "")
    {
        if (!isset($obj->id)) {
            $bool = $this->ObjectSqlInsert($obj, $tablename);
        } else {
            $bool = $this->ObjectSqlUpdate($obj, $tablename);
        }
        return $bool;
    }

    function ObjectSqlDelete($tablename, $id)
    {

        $sql = "DELETE FROM " . $tablename . " WHERE id = ?";
        echo $sql;
        $res = $this->link->prepare($sql);
        $res->bindValue(1, $id);
        if ($bools = $res->execute())
            return $bools;

    }

    function DbCount($sql)
    {

        $res = $this->link->query($sql);
        $rowCount = $res->rowCount();
        if (!$rowCount) {
            $rowCount = 0;
        }
        return $rowCount;
    }

    function DbQuery($sql, $pk = "")
    {

        $res = $this->link->prepare($sql);
        $res->execute();
        if ($res === TRUE || $res === FALSE) {

            return $res;
        }
        if ($res) {

            if ($res->rowCount() == 0)
                return false;

            $ret = array();
            $res->setFetchMode(PDO::FETCH_ASSOC);
            while ($row = $res->fetch()) {
                if (is_array($row) && count($row)) {
                    if ($pk == "")
                        $ret[] = $row;
                    else
                        $ret[$row[$pk]] = $row;

                }
            }
            return $ret;
        }
        return FALSE;
    }
}

?>